'''
This file is part of DopplerShift.

    DopplerShift is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    DopplerShift is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with DopplerShift.  If not, see <http://www.gnu.org/licenses/>.
'''
from twisted.web.resource import Resource
from dopplershift.core.containers.mediator import getMediator
from dopplershift.collector.exc import Http404
from dopplershift.collector.http import REQUEST_METHOD_GET, REQUEST_METHOD_POST, REQUEST_METHOD_NONE
from twisted.python import log
from lxml import etree

def find_and_render(request, method=REQUEST_METHOD_GET):
    mediator = getMediator()
    router = mediator.get("CollectorRoutes")
    try:
        handler = router.getHandler(request)
        return handler.work(method)
    except Http404 as e:
        return getMediator().get('ErrorRender').error_render(request, 404, as_string=True)

class CollectorResource(Resource):
    isLeaf = True
    _url = None
    def render_GET(self, request):
        log.msg("[GET] %s"%str(request))
        res = find_and_render(request)
        if res: return res
        return ":)"
    def render_POST(self, request):
        res = find_and_render(request, method=REQUEST_METHOD_POST)
        if res: return res
        return ":)"